package com.yc.starter.vcode.web;

import com.yc.starter.vcode.config.VcodeProperties;
import com.yc.starter.vcode.dto.Result;
import com.yc.starter.vcode.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/10
 * @email haijunzhou@hnit.edu.cn
 */
@RestController
@RequestMapping("vcode")
public class VcodeDo {

    // 生成图形验证码

    @RequestMapping(path = "image", produces = MediaType.IMAGE_PNG_VALUE)
    public void image(HttpServletResponse response,
                      HttpSession session) throws IOException {
        String vcode = VerifyCodeUtils.outputImage(200, 80, 4, response);
        session.setAttribute("vcode", vcode);
    }

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    VcodeProperties properties;

    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(properties.getFromEmail());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    // 发送邮箱验证码
    @RequestMapping(path = "email", produces = MediaType.IMAGE_PNG_VALUE)
    public Result email(HttpSession session, String toEmail,
               String title, String content) throws IOException {
        String vcode = System.currentTimeMillis()+ "";
        vcode = vcode.substring(vcode.length() - 4);
        session.setAttribute("vcode", vcode);
        // content : 请输入验证码:1234, 验证码 %s 已经发送到...
        content = content.contains("%s") ? String.format(content, vcode) : (content + vcode);
        sendSimpleMail(toEmail,title, content);
        return new Result(1,"验证码发送成功!", null);
    }


}
